package net.sf.midollo.io.lcdui.alert;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;

public class AlertOutputStream extends OutputStream {

  protected final Display display;
  protected final String title;
  protected final AlertType alertType;
  protected byte[] buffer;

  public AlertOutputStream(Display display) {
    this(display, "Info", AlertType.INFO);
  }

  public AlertOutputStream(Display display, String title) {
    this(display, title, AlertType.INFO);
  }

  public AlertOutputStream(Display display, String title, AlertType alertType) {
    this.display = display;
    this.title = title;
    this.alertType = alertType;
  }

  public void write(int b) throws IOException {
    write(new byte[] { (byte)b }, 0, 1);
  }

  public void write(byte[] b) throws IOException {
    write(b, 0, b.length);
  }

  public void write(byte[] b, int off, int len) throws IOException {
    if (this.buffer == null) {
      this.buffer = new byte[len];
      System.arraycopy(b, off, this.buffer, 0, len);
    } else {
      byte[] bufferNew = new byte[this.buffer.length + len];
      System.arraycopy(this.buffer, 0, bufferNew, 0, this.buffer.length);
      System.arraycopy(b, off, bufferNew, this.buffer.length, len);
      this.buffer = bufferNew;
    }
  }

  public void flush() throws IOException {
    if (this.buffer != null && this.buffer.length > 0) {
      String msg = new String(this.buffer);
      if (msg.length() > 0) {
        this.buffer = null;
        Alert alert = new Alert("Info", msg, null, AlertType.INFO);
        alert.setTimeout(Alert.FOREVER);
        this.display.setCurrent(alert);
      }
    }
  }
}
